package com.aw.baselib.util

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.aw.baselib.interfaces.IPermissionListener
import com.aw.baselib.util.AwLog.d
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.functions.Consumer

/**
 * Created by hzw
 */
class AwRxPermissionUtil private constructor() {
    /**
     * 判断权限集合
     * permissions 权限数组
     * return true-表示没有改权限  false-表示权限已开启
     */
    fun hasStoragePermission(mContexts: Context): Boolean {
        for (permission in storagePermissions) {
            if (!lacksPermission(mContexts, permission)) {
                return false
            }
        }
        return true
    }

    fun hasLocationPermission(context: Context): Boolean {
        for (permission in permissionsLocation) {
            if (!lacksPermission(context, permission)) {
                return false
            }
        }
        return true
    }

    fun hasNotificationPermission(context: Context): Boolean {
        for (permission in permissionsNotification) {
            if (!lacksPermission(context, permission)) {
                return false
            }
        }
        return true
    }

    fun hasPhonePermission(context: Context): Boolean {
        for (permission in permissionsPhone) {
            if (!lacksPermission(context, permission)) {
                return false
            }
        }
        return true
    }

    fun hasCameraPermission(context: Context): Boolean {
        for (permission in permissionsCamera) {
            if (!lacksPermission(context, permission)) {
                return false
            }
        }
        return true
    }

    fun hasBluetoothPermission(mContexts: Context): Boolean {
        for (permission in bluetoothPermissions) {
            if (!lacksPermission(mContexts, permission)) {
                return false
            }
        }
        return true
    }

    fun checkPermissions(
        activity: Activity?,
        permissions: Array<String>,
        listener: IPermissionListener?
    ) {
        val rxPermissions = RxPermissions(activity!!)
        rxPermissions.request(*permissions)
            .subscribe(object : Consumer<Boolean> {
                @Throws(Exception::class)
                override fun accept(aBoolean: Boolean) {
                    if (listener == null) return
                    if (aBoolean) {
                        //当所有权限都允许，才会到这里
                        listener.granted()
                    } else {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                activity, permissions[0]!!
                            )
                        ) {
                            listener.shouldShowRequestPermissionRationale()
                        } else {
                            listener.needToSetting()
                        }
                    }
                }
            })
    }

    //TODO 2025/10/30 有些问题,编译不通过
//    fun checkEachPermission(
//        activity: Activity?,
//        permissions: Array<String?>,
//        consumer: Consumer<*>?
//    ) {
//        val rxPermissions = RxPermissions(activity!!)
//        rxPermissions.requestEach(*permissions).subscribe(consumer)
//    }

    // 提供默认的 Consumer
    private fun getDefaultConsumer(): Consumer<Permission> {
        return Consumer { permission ->
            if (permission.granted) {
                // 权限已授予
                println("权限 ${permission.name} 已授予")
            } else if (permission.shouldShowRequestPermissionRationale) {
                // 用户拒绝但未选择"不再询问"
                println("权限 ${permission.name} 被拒绝，可以再次请求")
            } else {
                // 用户拒绝并选择"不再询问"
                println("权限 ${permission.name} 被永久拒绝")
            }
        }
    }

    /**
     * 参考
     * @param activity
     * @param permissions
     * @param listener
     */
    private fun checkEachPermissionTemplate(
        activity: Activity,
        permissions: Array<String>,
        listener: IPermissionListener
    ) {
        //        RxPermissions rxPermissions = new RxPermissions(activity);
        //        rxPermissions.requestEach(permissions)
        //                .subscribe(new Consumer<Permission>() {
        //                    @Override
        //                    public void accept(Permission permission) throws Exception {
        //                        if (permission.name.equals(Manifest.permission.CAMERA)) {
        //                            //使用permission.name可以获得指定权限获得后的操作
        //                            Toast.makeText(OneByOneActivity.this,
        //                                    "照相机权限授权了", Toast.LENGTH_SHORT).show();
        //                        }
        //                        /**
        //                         * 这里需要注意，当我们使用requestEach后，上面对应的权限，
        //                         * 下面都会执行一遍
        //                         *
        //                         * 例如，你上面8个权限都同意后，然后到达这里，
        //                         * 在走8次的permission.granted的判断语句
        //                         *
        //                         * 因此，使用时再加上permission.name判断一下更为合理
        //                         */
        //                        if (permission.granted) {
        //                            //用户已经同意该权限
        //                            Toast.makeText(OneByOneActivity.this,
        //                                    "用户已经同意该权限", Toast.LENGTH_SHORT).show();
        //
        //                        } else if (permission.shouldShowRequestPermissionRationale) {
        //                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,
        //                            // 那么下次再次启动时，还会提示请求权限的对话框
        //                            Toast.makeText(OneByOneActivity.this,
        //                                    "用户拒绝了该权限，没选中『不再询问』", Toast.LENGTH_SHORT).show();
        //
        //                        } else {
        //                            // 用户拒绝了该权限，并且选中『不再询问』
        //                            Toast.makeText(OneByOneActivity.this,
        //                                    "用户拒绝了该权限，并且选中『不再询问』", Toast.LENGTH_SHORT).show();
        //                        }
        //
        //                    }
        //                });
    }

    companion object {
        var instance: AwRxPermissionUtil? = null
            get() {
                if (field == null) {
                    field = AwRxPermissionUtil()
                }
                return field
            }
            private set
        var permissionApp = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.CAMERA,
            Manifest.permission.CALL_PHONE
        )

        /**
         * 读写权限  自己可以添加需要判断的权限, android 13以上
         */
        var permissionAppLatest = arrayOf(
            Manifest.permission.READ_MEDIA_IMAGES,
            Manifest.permission.READ_MEDIA_AUDIO,
            Manifest.permission.READ_MEDIA_VIDEO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.POST_NOTIFICATIONS,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_ADVERTISE,
            Manifest.permission.BLUETOOTH_CONNECT
        )

        /**
         * 读写权限  自己可以添加需要判断的权限
         */
        var permissionsStorage = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )

        /**
         * 读写权限  自己可以添加需要判断的权限, android 13以上
         */
        var permissionsStorageLatest = arrayOf(
            Manifest.permission.READ_MEDIA_IMAGES,  //            Manifest.permission.READ_MEDIA_AUDIO,
            Manifest.permission.READ_MEDIA_VIDEO
        )

        /**
         * 位置权限
         */
        var permissionsLocation = arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )

        /**
         * 相机权限
         */
        var permissionsCamera = arrayOf(
            Manifest.permission.CAMERA
        )

        /**
         * 通知权限
         */
        var permissionsNotification = arrayOf(
            Manifest.permission.POST_NOTIFICATIONS
        )

        /**
         * 通知权限
         */
        var permissionsInstallPackage = arrayOf(
            Manifest.permission.REQUEST_INSTALL_PACKAGES
        )

        /**
         * 电话权限
         */
        var permissionsPhone = arrayOf(
            Manifest.permission.CALL_PHONE
        )

        /**
         * 蓝牙权限
         */
        var permissionsBluetooth = arrayOf(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )

        /**
         * 蓝牙权限, android 12以上
         */
        var permissionsBluetoothLatest = arrayOf(
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_ADVERTISE,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
        val appAllPermissions: Array<String>
            get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permissionAppLatest
            } else {
                permissionApp
            }
        val storagePermissions: Array<String>
            get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permissionsStorageLatest
            } else {
                permissionsStorage
            }
        val bluetoothPermissions: Array<String>
            get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                permissionsBluetoothLatest
            } else {
                permissionsBluetooth
            }

        /**
         * 判断是否缺少权限
         */
        private fun lacksPermission(mContexts: Context, permission: String): Boolean {
            d("lacksPermission===> $permission")
            return ContextCompat.checkSelfPermission(
                mContexts,
                permission
            ) == PackageManager.PERMISSION_GRANTED
        }

        fun toAppSetting(activity: Activity) {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.data = Uri.parse("package:" + activity.packageName)
            activity.startActivity(intent)
        }
    }
}